import Vue from 'vue'
import VueRouter from 'vue-router'
import menuList from '../utils/menu.js'
import Main from '@/components/layout/index.vue'
import astgo from '../assets/js/astgo.js'

Vue.use(VueRouter)

const routes = [{
  path: '/',
  name: '/',
  component: Main,
  meta: {
    auth: true
  },
  children: [{
    path: '/',
    meta: {
      auth: true
    },
    component: () => import('@/views/home/index.vue')
  }]
},
{
  path: '/login',
  component: () => import('@/views/Login.vue')
  // component: () => import('@/views/mobile/Login.vue')
},
{
  path: '*', // 404 页面
  component: () => import('@/views/404.vue')
}
]

var Breadcrumb = JSON.parse(astgo.getItem('ys_prj_info_role')) || [] // 1权限设置路由

if (!Breadcrumb) {
  Breadcrumb = []
}

menuList.forEach(item => {
  if (!item.children) {
    if (item.id) {
      if (Breadcrumb.indexOf(item.id) || item.id === '0') {
        routes.push({
          path: item.path,
          component: Main,
          meta: {
            auth: true
          },
          children: [{
            path: item.path,
            meta: {
              auth: true
            },
            component: () => import('@/views' + item.path)
          }]
        })
      }
    }
  } else {
    item.children.forEach(i => {
      if (i.id) {
        if (Breadcrumb.indexOf(i.id) || item.id === '0') {
          routes.push({
            path: item.path,
            component: Main,
            meta: {
              auth: true
            },
            children: [{
              path: i.path,
              meta: {
                auth: true
              },
              component: () => import('@/views' + i.path)
            }]
          })
        }
      }
    })
  }
})

console.log('menuList', menuList)
console.log('menuList', routes)
// eslint-disable-next-line no-tabs
// id： 5 admin	6经理  7机器操作员

// id： 1权限设置 8账号管理  14机器组管理  19操作员管理  24机器管理

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  console.log(to)

  if (to.matched.some(res => res.meta.auth)) { // 判断是否需要登录权限
    // if (localStorage.getItem('ys_prj_info')) { // 判断是否登录
    if (sessionStorage.getItem('ys_prj_info')) { // 判断是否登录
      next()
    } else { // 没登录则跳转到登录界面
      next('/login')
    }
  } else {
    next()
  }
})

export default router
